package edu.sctu.lab03;

import javax.management.AttributeNotFoundException;
import javax.management.DynamicMBean;
import javax.management.MBeanException;
import javax.management.ReflectionException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class UserAdd extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        DynamicMBean session = null;
        try {
            if(session.getAttribute("isLogin")==null){
                resp.sendRedirect("login.jsp");
            }
        } catch (AttributeNotFoundException e) {
            e.printStackTrace();
        } catch (MBeanException e) {
            e.printStackTrace();
        } catch (ReflectionException e) {
            e.printStackTrace();
        }

        req.setCharacterEncoding("utf-8");

        String username=req.getParameter("username");
        String password=req.getParameter("password");


        //链接数据库
        Connection connection=null;
        PreparedStatement preparedStatement=null;

        //注册数据库
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //获取链接
        try {
            connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/sctu_javaweb_2018?serverTimezone=UTC",
                    "root",
                    "123456"
            );
        } catch (SQLException e) {
            e.printStackTrace();
        }

        //数据库指令
        String sql="insert into t_users(username,password) values(?,?)";

        //发送sql语句
        try {
            preparedStatement=connection.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        //插入到具体地方
        try {
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            preparedStatement.executeUpdate();
            connection.close();
            preparedStatement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        req.getRequestDispatcher("/userAdd.jsp").forward(req,resp);

    }
}
